<template>
  <a-row :gutter="10">
    <a-col :span="12">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="角色名称">
                  <a-input placeholder="请输入角色名称" v-model="queryParam.roleName"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="2">
              <span style='float: left;overflow: hidden;margin-top: 5px;' class='table-page-search-submitButtons'>
                <a-button type='primary' size='small' @click='searchQuery' icon='search'>查询</a-button>
                <a-button type='primary' size='small' @click='searchReset' icon='reload'
                          style='margin-left: 8px'>重置</a-button>
              </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <!-- table区域-begin -->
        <div>
          <div class="show-name">
            <div class="show-header">
              <div class="show-capsule">
                <div class="show-tag">
                  <a-icon type="team"/>
                </div>
                <div class="show-tagTwo">
                  已选角色
                  {{ selectionRowsNameList && selectionRowsNameList.length !== 0 ? selectionRowsNameList.length : '' }}
                </div>
              </div>
              <div class="show-clear">
                <a-button type="primary" shape="circle" icon="delete" @click="onClearSelectedAll"/>
              </div>
            </div>
            <div class="show-content">
              <div v-for="(item,index) in selectionRowsNameList" :key="item.id">
                <a-tag :color="item.color" style="margin-top: 5px" closable @close="()=>handleCloseTag(item.id)">
                  {{ item.name }}
                </a-tag>
              </div>
            </div>
          </div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect:onSelectSingle,onSelectAll:onSelectAll}'
            @change="handleTableChange">

            <span slot="description" slot-scope="text, record">
               <j-ellipsis :value="text" :length="10"/>
           </span>

          </a-table>
        </div>
        <!-- table区域-end -->
      </a-card>
    </a-col>
    <a-col :span="12">
      <batch-role-permission-modal ref="batchRolePermission" @ok="modalFormOk"></batch-role-permission-modal>
    </a-col>
  </a-row>
</template>

<script>
import BatchRolePermissionModal from "./modules/batchRolePermissionModal";
import {filterObj} from '@/utils/util'
import {deleteAction, getAction, downFile, postAction} from '@/api/manage'
import JEllipsis from "../../components/jeecg/JEllipsis";

export default {
  name: "batchRolePermissionList",
  components: {JEllipsis, BatchRolePermissionModal},
  data() {
    return {
      description: '菜单批量授权页面',
      url: {
        list: "/sys/role/list",
      },
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '角色名称',
          align: 'center',
          dataIndex: 'roleName'
        },
        {
          title: '角色编码',
          align: 'center',
          dataIndex: 'roleCode'
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'description',
          scopedSlots: {customRender: 'description'}
        },
      ],
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 15,
        pageSizeOptions: ['15', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectionRowsName: '',            //用来显示选择的所有人员
      selectionRowsNameList: [],            //用来显示选择的所有人员数组
      selectedRowsPlusPro: [],   //这里是解决Table组件selectedRows翻页后不保留上一页已选中items的解决方案
    }
  },
  created() {
    this.loadData();
  },
  methods: {
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams(); //查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      if (this.columns) {
        this.columns.forEach(function (value) {
          str += ',' + value.dataIndex
        })
      }
      return str
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if(isNaN(pagination.pageSize)){
        pagination.pageSize = Number(pagination.pageSizeOptions[0])
      }
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    onClearSelectedAll() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.selectionRowsName = ''
      this.selectionRowsNameList = []
      this.selectedRowsPlusPro = []
      this.$refs.batchRolePermission.show()
    },
    searchQuery() {
      this.loadData(1)
    },
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    /*Table组件selectedRows翻页后不保留上一页已选中items的解决方案  用户手动选择/取消选择某列的回调*/
    onSelectSingle(record, selected, selectedRows, nativeEvent) {
      //选中之后
      if (selected) {
        let selectedRowsPlus = this.selectedRowsPlusPro
        selectedRowsPlus.push(record)
      }
      //去掉选中
      if (!selected) {
        let delIndex = null
        for (let i = 0; i < this.selectedRowsPlusPro.length; i++) {
          if (this.selectedRowsPlusPro[i].id == record.id) {
            delIndex = i
            break
          }
        }
        this.selectedRowsPlusPro.splice(delIndex, 1)
      }
      this.handlePageSize()
    },
    /*Table组件selectedRows翻页后不保留上一页已选中items的解决方案  用户手动选择/取消选择所有列的回调*/
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected) {
        this.selectedRowsPlusPro = this.selectedRowsPlusPro.concat(changeRows)
      }
      if (!selected) {
        /*深拷贝*/
        let selectedRowsPlusPro = JSON.parse(JSON.stringify(this.selectedRowsPlusPro))
        let delIndex = []
        for (let i = 0; i < selectedRowsPlusPro.length; i++) {
          for (let j = 0; j < changeRows.length; j++) {
            if (changeRows[j].id == selectedRowsPlusPro[i].id) {
              delIndex.push(i)
              break
            }
          }
        }
        for (let k = 0; k < delIndex.length; k++) {
          delete selectedRowsPlusPro[delIndex[k]]
        }
        let pureProductListSelected = selectedRowsPlusPro.filter((item => {
          return item != undefined
        }))
        this.selectedRowsPlusPro = pureProductListSelected
      }
      this.handlePageSize()
    },
    /*处理Table组件selectedRows翻页后不保留上一页已选中items的解决方案*/
    handlePageSize(flag) {
      var rowsName = []
      if (this.selectedRowKeys.length !== 0) {
        if (this.selectedRowsPlusPro.length !== 0) {
          for (var h = 0; h < this.selectedRowKeys.length; h++) {
            for (var a = 0; a < this.selectedRowsPlusPro.length; a++) {
              if (this.selectedRowKeys[h] === this.selectedRowsPlusPro[a].id) {
                rowsName.push(this.selectedRowsPlusPro[a].roleName)
              }
            }
          }
          this.selectionRowsName = rowsName + ''
          this.handleSelectRowList(this.selectionRowsName)
          this.$refs.batchRolePermission.show(this.selectedRowsPlusPro)
        } else {
          this.selectionRowsName = ''
          this.selectionRowsNameList = []
          this.$refs.batchRolePermission.show()
        }
      } else {
        this.selectionRowsName = ''
        this.selectionRowsNameList = []
        this.$refs.batchRolePermission.show()
      }
    },
    modalFormOk() {
      this.onClearSelectedAll()
      this.loadData()
    },
    handleSelectRowList(selectionRowsName) {
      var finallList = []     //最终展示的数组
      var list = selectionRowsName ? selectionRowsName.split(',') : []
      var initColorList = ['orange', 'green', 'cyan', 'blue', 'purple', 'volcano', 'geekblue', 'pink', 'red']
      var tagColorList = []    //颜色数组
      if (list.length > initColorList.length) {
        var shang = (list.length / initColorList.length)
        let yushu = list.length % initColorList.length
        if (shang) {    //有商
          //根据shang的长度去往tagColorList数组中push相同的几倍
          for (var h = 0; h < shang; h++) {
            initColorList && initColorList.forEach((item) => {
              tagColorList.push(item)
            })
          }
          if (yushu) {  //有余数
            var leftList = []
            leftList = initColorList.splice(0, yushu)
            tagColorList = tagColorList.concat(leftList)
          }
        } else {
          if (yushu) {  //有余数
            var leftList = []
            leftList = initColorList.splice(0, yushu)
            tagColorList = leftList
          }
        }
      } else {
        tagColorList = ['orange', 'green', 'cyan', 'blue', 'purple', 'volcano', 'geekblue', 'pink', 'red']
      }
      if (list && list.length !== 0) {
        for (var i = 0; i < list.length; i++) {
          var items = {
            name: list[i],
            color: tagColorList[i],
            id: this.selectedRowsPlusPro[i].id
          }
          finallList.push(items)
          this.selectionRowsNameList = finallList
        }
      } else {
        this.selectionRowsNameList = []
      }
    },
    handleCloseTag(tagId) {
      this.selectedRowKeys = this.selectedRowKeys && this.selectedRowKeys.length !== 0 ? this.selectedRowKeys.filter(item => item !== tagId) : []
      this.selectionRows = this.selectionRows && this.selectionRows.length !== 0 ? this.selectionRows.filter(item => item.id !== tagId) : []
      // this.selectionRowsNameList = this.selectionRowsNameList && this.selectionRowsNameList.length !== 0 ? this.selectionRowsNameList.filter(item => item.id !== tagId) : []
      this.selectedRowsPlusPro = this.selectedRowsPlusPro && this.selectedRowsPlusPro.length !== 0 ? this.selectedRowsPlusPro.filter(item => item.id !== tagId) : []
      var userNames = this.selectedRowsPlusPro.map((obj, index) => {
        return obj.roleName
      }).join(',')
      this.selectionRowsName = userNames
      this.handleSelectRowList(this.selectionRowsName)
      this.$refs.batchRolePermission.show(this.selectedRowsPlusPro)
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .ant-alert {
  padding: 8px 15px 8px 25px;
}

.show-name {
  width: 100%;
  background-color: #f1f1f1;
  color: #727272;
  padding: 8px;
  border-radius: 3px;
  display: block;
  box-sizing: border-box;
  margin: 0 0 10px 0;
  box-sizing: border-box;

  .show-header {
    width: 100%;
    height: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: nowrap;

    .show-capsule {
      display: inline-flex;
      vertical-align: middle;
      border-radius: 5px;
      box-sizing: border-box;

      .show-tag {
        font-size: 16px;
        vertical-align: middle;
        position: relative;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        padding: 0px 8px;
        height: 28px;
        font-family: Helvetica Neue, Helvetica, sans-serif;
        white-space: nowrap;
        background-color: #0081ff;
        color: #ffffff;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
        margin: 0;
      }

      .show-tagTwo {
        font-size: 12px;
        vertical-align: middle;
        position: relative;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        padding: 0px 8px;
        height: 28px;
        font-family: Helvetica Neue, Helvetica, sans-serif;
        white-space: nowrap;
        color: #0081ff;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
        border: 1px solid #0081ff;
      }
    }
  }

  .show-content {
    width: 100%;
    height: auto;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
  }
}

/deep/ .ant-tag .anticon-close {
  color: #0081ff;
}
</style>